package com.ustcinfo.study.hbase.xujianan;

import com.mysql.jdbc.Connection;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCUtil {

    private static Connection conn;


    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/test";
    //MySQL配置时的用户名
    private static String user = "root";
    //MySQL配置时的密码
    private static String password = "Xujn04031401*";

    /*
     *获取连接
     */
    public static Connection getCon() throws ClassNotFoundException {
        //加载驱动程序
        Class.forName(driver);
        //1.getConnection()方法，连接MySQL数据库！
        try {
            conn = (Connection) DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /*
     * 获取数据映射<id,value>
     * */
    public static Map<Integer, String> getStrMap(String sql) {
        Map<Integer, String> map = new HashMap<>();

        Statement stat = null;
        ResultSet rs = null;

        try {
            stat = getCon().createStatement();
            rs = stat.executeQuery(sql);

            while (rs.next()) {
                String s = rs.getString(2);
//                去除null
                if (s == null) {
                    s = "";
                }
                map.put(rs.getInt(1), s);
            }
            rs.close();
            stat.close();
            conn.close();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return map;
    }

}







